<template>
  <transition name="slide">
    <music-list :songs="songs" :title="title" :bg-image="bgImage" />
  </transition>
</template>

<script>
import MusicList from '../music-list/MusicList'
import { mapGetters } from 'vuex'
import { getSingerDetail, getSongsUrls } from '@/api/index'
import { createSong } from '@/assets/js/song.js'

export default {
  name: 'SingerDetail',
  data() {
    return {
      songs: []
    }
  },
  computed: {
    title() {
      return this.singer.name
    },
    bgImage() {
      return this.singer.picUrl
    },
    ...mapGetters([
      'singer'
    ])
  },
  created() {
    this._getSingerDetail()
  },
  methods: {
    _getSingerDetail() {
      // 做一个判断: 如果在singerDetail页面刷新的话, this.singer就变成空对象(因为singer数据是路由传递过来的), 返回歌手界面
      if (!this.singer.id) {
        this.$router.push('/singer')
        return
      }
      getSingerDetail({ id: this.singer.id }).then(res => {
        if (res.status === 200) {
          this.songs = this._normalizeSongs(res.data.hotSongs)
          return this.songs
        }
      }).then(songs => {
        const songsID = []
        songs.forEach(song => {
          songsID.push(song.id)
        })
        return songsID
      }).then(songsID => {
        return getSongsUrls({ id: songsID.join(',') })
      }).then(songsUrl => {
        for (let i = 0; i < songsUrl.data.data.length; i++) {
          this.songs[i].url = songsUrl.data.data[i].url
        }
      }).catch(err => {
        console.log(err)
      })
    },
    _normalizeSongs(list) {
      const ret = []
      list.forEach(item => {
        if (item.id) {
          ret.push(createSong(item))
        }
      })
      return ret
    }
  },
  components: {
    MusicList
  }
}
</script>

<style lang="scss" scoped>
@import "~@/assets/css/variable.scss";

.slide-enter-active, .slide-leave-active{
  transition: all .3s;
}
.slide-enter, .slide-leave-to{
  transform: translate3d(100%, 0, 0);
}
</style>